console.log("人物志页面脚本已加载");

document.addEventListener('DOMContentLoaded', () => {
    // “人物志”页面的交互逻辑将在这里初始化
    initializeBambooSlips();
    initializeSkillRadar();
    const main = document.querySelector('main');
    if(main) main.classList.add('fade-page-enter');
});

function initializeBambooSlips() {
    const container = document.getElementById('bamboo-container');
    if (!container) return;

    // 清空占位符
    container.innerHTML = '';

    resumeData.forEach(item => {
        const slip = document.createElement('div');
        slip.className = 'bamboo-slip';

        const content = `
            <div class="slip-title-vertical">${item.title}</div>
            <div class="slip-content">
                <h3>${item.title}</h3>
                <p>${item.content}</p>
            </div>
        `;
        slip.innerHTML = content;
        container.appendChild(slip);
    });
}

function initializeSkillRadar() {
    const container = d3.select("#radar-chart-container");
    if (container.empty()) {
        console.error("Radar chart container not found.");
        return;
    }
    container.html(''); // Clear the placeholder text

    const width = 800;
    const height = 500;
    const margin = { top: 60, right: 60, bottom: 60, left: 60 };
    const radius = Math.min(width, height) / 2 - Math.max(margin.top, margin.right);

    const data = [
        { axis: "前端 (北斗)", value: 0.9 },
        { axis: "后端 (玄武)", value: 0.7 },
        { axis: "数据库 (青龙)", value: 0.6 },
        { axis: "设计 (紫微)", value: 0.8 },
        { axis: "运维 (白虎)", value: 0.5 },
        { axis: "算法 (朱雀)", value: 0.75 }
    ];

    const svg = container.append("svg")
        .attr("width", width)
        .attr("height", height);
    const g = svg.append("g")
        .attr("transform", `translate(${width / 2}, ${height / 2})`)
        .attr("class", "radar-rotate-group");
    
    const rScale = d3.scaleLinear()
        .domain([0, 1])
        .range([0, radius]);

    const gridLevels = 5;
    g.selectAll(".grid-line")
        .data(d3.range(1, gridLevels + 1).reverse())
        .enter().append("circle")
        .attr("class", "grid-line")
        .attr("r", d => radius / gridLevels * d);

    const angleSlice = Math.PI * 2 / data.length;
    const axes = g.selectAll(".axis")
        .data(data)
        .enter().append("g")
        .attr("class", "axis");

    axes.append("line")
        .attr("x1", 0).attr("y1", 0)
        .attr("x2", (d, i) => rScale(1.1) * Math.cos(angleSlice * i - Math.PI / 2))
        .attr("y2", (d, i) => rScale(1.1) * Math.sin(angleSlice * i - Math.PI / 2))
        .attr("class", "axis-line");

    axes.append("text")
        .attr("class", "axis-label")
        .attr("text-anchor", "middle")
        .attr("dy", "0.35em")
        .attr("x", (d, i) => rScale(1.2) * Math.cos(angleSlice * i - Math.PI / 2))
        .attr("y", (d, i) => rScale(1.2) * Math.sin(angleSlice * i - Math.PI / 2))
        .text(d => d.axis);

    // 动画：初始全部点收缩到中心，依次弹性展开
    const radarLine = d3.lineRadial()
        .curve(d3.curveCardinalClosed)
        .radius(d => rScale(d.value))
        .angle((d, i) => i * angleSlice);

    // 初始状态：所有点都在中心
    const initialData = data.map(d => ({ ...d, value: 0 }));
    const radarArea = g.append("path")
        .datum(initialData)
        .attr("class", "radar-area")
        .attr("d", radarLine)
        .style("fill", "url(#radar-gradient)")
        .style("stroke", "url(#radar-stroke)")
        .style("stroke-width", 3)
        .style("filter", "drop-shadow(0 0 32px #3a5a6c88) blur(1.5px)");

    // 渐变定义
    const defs = svg.append("defs");
    defs.append("radialGradient")
        .attr("id", "radar-gradient")
        .attr("cx", "50%").attr("cy", "50%").attr("r", "70%")
        .selectAll("stop")
        .data([
            {offset: "0%", color: "#fffbe6", opacity: 0.18},
            {offset: "60%", color: "#3a5a6c", opacity: 0.13},
            {offset: "100%", color: "#3a5a6c", opacity: 0.04}
        ])
        .enter().append("stop")
        .attr("offset", d => d.offset)
        .attr("stop-color", d => d.color)
        .attr("stop-opacity", d => d.opacity);
    defs.append("linearGradient")
        .attr("id", "radar-stroke")
        .attr("x1", "0").attr("y1", "0").attr("x2", "1").attr("y2", "1")
        .selectAll("stop")
        .data([
            {offset: "0%", color: "#b0a084"},
            {offset: "100%", color: "#3a5a6c"}
        ])
        .enter().append("stop")
        .attr("offset", d => d.offset)
        .attr("stop-color", d => d.color);

    // 动画展开
    radarArea.transition()
        .duration(1200)
        .ease(d3.easeElasticOut.period(0.7))
        .attrTween("d", function() {
            const interp = d3.interpolateArray(initialData, data);
            return function(t) {
                return radarLine(interp(t));
            };
        });

    // 网格线
    g.selectAll(".grid-line")
        .attr("fill", "none")
        .attr("stroke", "#b0a084")
        .attr("stroke-opacity", 0.18)
        .attr("stroke-width", 1.5);
    // 轴线
    g.selectAll(".axis-line")
        .attr("stroke", "url(#radar-stroke)")
        .attr("stroke-width", 2.2)
        .attr("stroke-opacity", 0.32);
    // 轴标签
    g.selectAll(".axis-label")
        .attr("font-family", "var(--font-title)")
        .attr("font-size", "1.08rem")
        .attr("fill", "#3a5a6c")
        .attr("font-weight", "bold")
        .style("text-shadow", "0 2px 8px #fffbe6cc");

    // 点初始在中心
    const points = g.selectAll(".radar-point")
        .data(data)
        .enter().append("circle")
        .attr("class", "radar-point")
        .attr("r", 6)
        .attr("cx", 0)
        .attr("cy", 0)
        .style("fill", "#fffbe6")
        .style("stroke", "#b0a084")
        .style("stroke-width", 3)
        .style("filter", "drop-shadow(0 0 8px #b0a08488)")
        .style("cursor", "pointer");

    // 弹性动画依次展开点
    points.transition()
        .delay((d, i) => 300 + i * 120)
        .duration(900)
        .ease(d3.easeElasticOut.period(0.7))
        .attr("cx", (d,i) => rScale(d.value) * Math.cos(angleSlice*i - Math.PI/2))
        .attr("cy", (d,i) => rScale(d.value) * Math.sin(angleSlice*i - Math.PI/2));

    // 悬停交互：高亮点并显示技能值气泡
    points.on("mouseenter", function(event, d) {
        d3.select(this)
            .transition().duration(200)
            .attr("r", 12)
            .style("fill", "#c23b23")
            .style("stroke", "#fffbe6");
        // 气泡
        g.append("text")
            .attr("class", "radar-tooltip")
            .attr("x", d3.select(this).attr("cx"))
            .attr("y", d3.select(this).attr("cy") - 18)
            .attr("text-anchor", "middle")
            .attr("font-size", "1.2rem")
            .attr("fill", "#c23b23")
            .attr("font-weight", "bold")
            .style("text-shadow", "0 2px 8px #fffbe6cc")
            .text((d.value * 100).toFixed(0) + "%");
    })
    .on("mouseleave", function(event, d) {
        d3.select(this)
            .transition().duration(200)
            .attr("r", 6)
            .style("fill", "#fffbe6")
            .style("stroke", "#b0a084");
        g.selectAll(".radar-tooltip").remove();
    });

    // 自动旋转动画
    let angle = 0;
    function rotateRadar() {
        angle = (angle + 0.2) % 360;
        g.attr("transform", `translate(${width / 2}, ${height / 2}) rotate(${angle})`);
        requestAnimationFrame(rotateRadar);
    }
    setTimeout(() => {
        rotateRadar();
    }, 1400); // 等待弹性动画结束后再开始旋转
}

// 水墨祥云动态背景（人物志专用）
(function() {
  const canvas = document.getElementById('about-bg-canvas');
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  let width = window.innerWidth;
  let height = window.innerHeight;
  function resize() {
    width = window.innerWidth;
    height = window.innerHeight;
    canvas.width = width;
    canvas.height = height;
  }
  resize();
  window.addEventListener('resize', resize);

  // 祥云参数
  const clouds = Array.from({length: 5}, (_,i) => ({
    x: Math.random()*width,
    y: Math.random()*height*0.7+height*0.1,
    r: 120+Math.random()*120,
    dx: -0.08+Math.random()*0.16,
    dy: -0.04+Math.random()*0.08,
    alpha: 0.10+Math.random()*0.10,
    t: Math.random()*Math.PI*2
  }));

  function drawCloud(cx, cy, r, alpha, isNight) {
    ctx.save();
    ctx.globalAlpha = alpha;
    const grad = ctx.createRadialGradient(cx, cy, r*0.2, cx, cy, r);
    grad.addColorStop(0, isNight ? '#222' : '#b0a084');
    grad.addColorStop(0.5, isNight ? '#3a5a6c' : '#f7f1e3');
    grad.addColorStop(1, 'rgba(255,255,255,0)');
    ctx.beginPath();
    for(let i=0;i<7;i++){
      const angle = Math.PI*2/7*i + Math.sin(Date.now()/1800+i)*0.18;
      const rr = r*0.7 + Math.sin(Date.now()/1200+i)*r*0.08;
      ctx.arc(cx+Math.cos(angle)*rr, cy+Math.sin(angle)*rr, r*0.22, 0, Math.PI*2);
    }
    ctx.closePath();
    ctx.fillStyle = grad;
    ctx.filter = 'blur(8px)';
    ctx.fill();
    ctx.restore();
  }

  function draw() {
    ctx.clearRect(0,0,width,height);
    const isNight = document.body.classList.contains('night-mode');
    clouds.forEach(c => {
      drawCloud(c.x, c.y, c.r, c.alpha*(isNight?1.5:1), isNight);
    });
  }

  function animate() {
    clouds.forEach(c => {
      c.x += c.dx + Math.sin(c.t)*0.18;
      c.y += c.dy + Math.cos(c.t)*0.12;
      c.t += 0.006+Math.random()*0.003;
      if (c.x < -c.r) c.x = width+c.r;
      if (c.x > width+c.r) c.x = -c.r;
      if (c.y < -c.r) c.y = height+c.r;
      if (c.y > height+c.r) c.y = -c.r;
    });
    draw();
    requestAnimationFrame(animate);
  }
  animate();

  // 夜间模式切换时重绘
  const obs = new MutationObserver(draw);
  obs.observe(document.body, {attributes:true, attributeFilter:['class']});
})();

// 人物志文化彩蛋气泡
(function() {
  const mainTitle = document.querySelector('.section-title');
  if (!mainTitle) return;
  let bubble;
  function showEgg() {
    if (bubble) return;
    bubble = document.createElement('div');
    bubble.className = 'cultural-egg-bubble';
    bubble.innerHTML = '文物小知识：竹简，古代书写载体，见证中华文明传承。';
    mainTitle.parentElement.appendChild(bubble);
    setTimeout(()=>{bubble.style.opacity=1; bubble.style.pointerEvents='auto';}, 80);
    setTimeout(hideEgg, 4200);
  }
  function hideEgg() {
    if (bubble) {
      bubble.style.opacity = 0;
      setTimeout(()=>{if(bubble) {bubble.remove(); bubble=null;}}, 400);
    }
  }
  mainTitle.addEventListener('mouseenter', showEgg);
  mainTitle.addEventListener('mouseleave', hideEgg);
  setTimeout(showEgg, 1200);
})(); 